package com.sangmo.fts.process.inventory.service;

import com.sangmo.boot.framework.common.errors.ServiceException;
import com.sangmo.boot.framework.common.errors.StandardErrors;
import com.sangmo.boot.framework.data.filter.PageResult;
import com.sangmo.boot.framework.data.filter.PageSearch;
import com.sangmo.boot.framework.data.filter.ValueFilter;
import com.sangmo.boot.framework.plugin.dataview.crud.service.DelegateViewService;
import com.sangmo.boot.framework.plugin.dataview.crud.service.ViewService;
import com.sangmo.fts.process.inventory.interfaces.IfStockConfirmRequest;
import com.sangmo.fts.process.inventory.model.IfStock;
import com.sangmo.fts.process.inventory.model.IfStockItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class IfStockService extends DelegateViewService<IfStock> {

    @Autowired
    private IfStockEntityService ifStockEntityService;

    @Autowired
    private IfStockDocumentService ifStockDocumentService;

    @Autowired
    private IfStockItemEntityService ifStockItemEntityService;

    @Override
    protected ViewService<IfStock> getEntityService() {
        return ifStockEntityService;
    }

    /*public void confirm(Long id, IfStockConfirmRequest request) {
        IfStock stock = this.find(id);
        ifStockDocumentService.createConfirmDoc(id, request.getFileUploadId());
        if (IfStock.States.INBOUND.equals(stock.getState())) {
            stock.setState(IfStock.States.PENDING);
            this.save(stock);
        }
    }*/

    public void approve(Long id) {
        IfStock stock = this.get(id);
        if (!IfStock.States.PENDING.equals(stock.getState())) {
            throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.ifStock.approve.state.wrong");
        }
        stock.setState(IfStock.States.CHECKED);
        this.save(stock);
    }

    public IfStock findByWaybillId(Long waybillId) {
        return ifStockEntityService.findByWaybillId(waybillId);
    }

    public List<IfStockItem> listItemsByStockId(Long stockId) {
        return ifStockItemEntityService.listByStockId(stockId);
    }

    public PageResult<IfStockItem> listItemsByPage(Long stockId, PageSearch ps) {
        ps.getFilters().add(new ValueFilter("stockId", ValueFilter.OP_EQ, stockId));
        return ifStockItemEntityService.search(ps);
    }

    public PageResult<IfStock> selection(PageSearch ps) {
        ps.getFilters().add(new ValueFilter("state", ValueFilter.OP_EQ, IfStock.States.CHECKED));
        return ifStockEntityService.search(ps);
    }

}
